import { ElMessage } from "element-plus";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import { findNewCartListAPI } from "@/apis/cart";
import { insertCartAPI,delCartAPI } from "@/apis/cart";

export const useCartStore = defineStore( 'carestore',()=>{
  const userStore = useUserStore()
  const isLogin = computed (()=>userStore.userInfo.token)
  const cartList = ref([])
  const addCareStore =async (goods)=>{
    //已添加过 count+1  没有则直接push
  const {skuId,count} = goods
  if (isLogin.value){
    await insertCartAPI ({skuId,count})
    updateNewList()
    // updateNewList()
    ElMessage.success('购物车添加成功')
  }else{
  const item = cartList.value.find((item)=>{goods.skuId === item.skuId})
    if(item){
      item.count++
      ElMessage.success('购物车添加成功')
    }else{
      cartList.value.push(goods)
      ElMessage.success('购物车添加成功')
    }
  }
  }
  const delCart = async (skuId) => {
    // 思路：
    // 1. 找到要删除项的下标值 - splice
    // 2. 使用数组的过滤方法 - filter
    if (isLogin.value){
      delCartAPI([skuId])
      updateNewList()
    }
    else {const idx = cartList.value.findIndex((item) => skuId === item.skuId)
    cartList.value.splice(idx, 1)
  updateNewList()}
}
//获取最新列表
const updateNewList = async ()=>{
  const res = await findNewCartListAPI()
  cartList.value = res.result
}
//单选功能
const singleCheck = (skuId, selected) => {
  // 通过skuId找到要修改的那一项 然后把它的selected修改为传过来的selected
  const item = cartList.value.find((item) => item.skuId === skuId)
  item.selected = selected
}
//全选功能
// 全选功能action
const allCheck = (selected) => {
  // 把cartList中的每一项的selected都设置为当前的全选框状态
  cartList.value.forEach(item => item.selected = selected)
}
//合计
const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
// 4. 已选择商品价钱合计
const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

// 是否全选计算属性
const isAll = computed(() => cartList.value.every((item) => item.selected))
//计算总价
const allCount = computed(()=> cartList.value.reduce((a,c) => a+c.count ,0))
const allCountPrice = computed(()=> cartList.value.reduce((a,c) => a+c.count*c.price ,0))

  return{
    allCount,
    allCountPrice,
    cartList,
    isAll,
    selectedCount,
    selectedPrice,
    addCareStore,
    delCart,
    singleCheck,
    allCheck
  }
},{
  persist:true
})
